/**
 * 
 */
package com.legrand.security.utils;


import com.legrand.core.entity.User;
import com.legrand.security.token.JwtAuthenticationToken;
import com.legrand.security.token.UserContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Locale;
import java.util.Optional;

/**
*@author xiah
*2018-07-11 09:54:20
*/
public class RequestUtil {
	
	private static final Locale DEFAULT_LOCALE = Locale.SIMPLIFIED_CHINESE;
	
	public static Integer getUserId() {
		Optional<UserContext> userContext = getUserContext();
		if(userContext.isPresent()){
			return userContext.get().getUserId();
		}
		return 0;
	}

	public static User getUser() {
        Optional<UserContext> userContext = getUserContext();
        return userContext.isPresent() ? userContext.get().getUser() : null ;
    }
	
	public static Optional<UserContext> getUserContext() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
            return Optional.of((UserContext) jwtAuthenticationToken.getPrincipal());
        }
        return Optional.empty();
    }

}
